/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.CustomerOrderEntity;
import ejb.CustomerOrderEntityFacade;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author mohan
 */
@WebServlet(name = "AddCustomerOrder", urlPatterns = {"/AddCustomerOrder"})
public class AddCustomerOrder extends HttpServlet {
    @EJB
    private CustomerOrderEntityFacade customerOrderEntityFacade;

    
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        String cusOrderID = request.getParameter("cusOrderID");
        
        String orderNo1 = "";
        String due_date1 = "";
        String comment1 =  "";
        String order_amount1 = "";
        String customerID1 = "";
        
        String out_msg ="";
        String orderNo = request.getParameter("orderNo"); 
        String due_date = request.getParameter("dueDate"); 
        String comment = request.getParameter("comment"); 
        String order_amount = request.getParameter("amount"); 
        String customerID = request.getParameter("customerID"); 
        
        String act = request.getParameter("act");
        
        String cusOrderKey = request.getParameter("cusOrderKey");
        AppOptions apo = new AppOptions();
        
        //To add a new customer order       
        if (act != null && act.equals("Add Customer Order")) 
        {
            //Check whether the fields are empty except the comment field 
            if(((! orderNo.isEmpty())) && ((! due_date.isEmpty()))  && (! order_amount.isEmpty()) && (! customerID.isEmpty()))
            {
                double amount = Double.parseDouble(order_amount);
                Long cusID = Long.parseLong(customerID);
                
                //check whether there is a customer with the given customerID
                if(apo.checkCustomer(cusID))
                {
                    if(! apo.checkCustomerOrder(orderNo))
                    {
                        try{
                            
                            CustomerOrderEntity coe = new CustomerOrderEntity();
                            coe.setAmount(amount);
                            coe.setComment(comment);
                            coe.setDueDate(due_date);
                            coe.setOrderno(orderNo);
                    
                            coe.setCustomerid(apo.getCustomer(cusID));
                    
                            customerOrderEntityFacade.create(coe);
                            out_msg = "Customer Order Details Inserted Successfully";
                
                        }
            
                        
                    
                        catch(Exception ex)
                        {
                            out_msg = "The Format of the Customer ID or Amount is Wrong!! Check it again";
                        }
                    }
                    
                    else
                    {
                        out_msg = "Already There is a order with the same Order No ";
                    }
                }
                
                else
                {
                    out_msg = "There is no any customer with the given Customer ID";
                }
            }
            
            else
            {
                out_msg = "Fill the necessary Fields correctly";
            }
        }
        
        //To update an existing customer order
        else if(act != null && act.equals("Update Customer Order"))
        {
            
            if((orderNo != null) && (due_date != null) && (comment != null) && (order_amount!=null) && (customerID != null))
            {
                
                double amount = Double.parseDouble(order_amount);
                Long cusID = Long.parseLong(customerID);
                
                //check whether there is a customer with the given customerID
                if(apo.checkCustomer(cusID))
                {
                    try{
                        
                        CustomerOrderEntity coe = customerOrderEntityFacade.find(cusOrderKey);
                        coe.setAmount(amount);
                        coe.setComment(comment);
                        coe.setDueDate(due_date);
                        coe.setCustomerid(apo.getCustomer(cusID));
                        customerOrderEntityFacade.edit(coe);
                        out_msg = "Customer Order Details Updated Successfully";
                    }
            
                   
                    
                    catch(Exception ex)
                    {
                        out_msg = "The Format of the Customer ID or Amount is Wrong!! Check it again";
                    }
                   
                }
                 
                else
                {
                    out_msg = "There is no any customer with the given Customer ID";
                }
            }
            
            else
            {
                out_msg = "Fill the necessary Fields correctly";
            }
            
        }
        
        //To get the customer ordr details of a specific customer order
        else  if (cusOrderID != null) 
        {
            List customerOrder = customerOrderEntityFacade.findAll();
            for(Iterator it = customerOrder.iterator(); it.hasNext();)
            {
                CustomerOrderEntity elem = (CustomerOrderEntity) it.next();
                if(elem.getOrderno().toString().equals(cusOrderID))
                {
                    orderNo1 = elem.getOrderno();
                    due_date1 = elem.getDueDate();
                    comment1 = elem.getComment();
                    order_amount1 = elem.getAmount()+"";
                    customerID1 = elem.getCustomerid().getCustomerid()+"";
                }
            }          
            
        }
        
        
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet AddCustomerOrder</title>");            
            out.println("</head>");
            out.println("<div align='center'>");
            out.println("<body bgcolor='#CCCCCC'>");
            out.println("<a href = 'Mainindex'>Main Window | </a>");
            out.println("<a href = 'AddCustomer'>Add new customer | </a>");
            out.println("<a href = 'ListCustomers'>View Customers | </a>");
            out.println("<a href = 'AddCustomerOrder'>Add new customer Order | </a>");
            out.println("<a href = 'ListCustomerOrders'>View Customers Orders</a>");
            
            out.println("<h1>Add/Update Customer Order Details</h1>");
            
            
            out.println("<form>");
            out.println("<table width='600' height='400' border='1'>");
            out.println("<tr>");
            out.println("<td>Order No :</td><td><input type ='text' name ='orderNo' value='"+orderNo1+"'></td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Customer Id :</td><td><input type ='text' name ='customerID' value='"+customerID1+"'></td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Amount : </td><td><input type ='text' name ='amount' value='"+order_amount1+"'></td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Due Date : </td><td><input type ='text' name ='dueDate' value='"+due_date1+"'></td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Comment : </td><td><textarea name = 'comment'>"+comment1+"</textarea></td>");
            out.println("</tr>");
            out.println("</table>");
            out.println("<br/>");
            out.println("<input type='hidden' name='cusOrderKey' value='"+cusOrderID+"'/>");
            out.println("<input type='submit' name='act' Value='Add Customer Order'>");
            out.println("<input type='submit' name='act' Value='Update Customer Order' ><br/>");
            out.println("<h3>"+out_msg+"</h3>");
            out.println("</form>");
            
            
            out.println("</body>");
            out.println("</div>");
            out.println("</html>");
        } finally {            
            out.close();
        }
        
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
